<?
    /* -*- Mode: PHP5; tab-width: 4; indent-tabs-mode: nil; basic-offset: 4 -*- */

    /*********************************************************
    *            --== InArch ==--
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @version n/a
    * @since 12.10.2005
    * @copyright essentialmind.com 2005
    *
    *********************************************************/
    
    /***
    * Class clientNodeFolder
    ****
    * This classs represents a folder
    ****
    * @package clientNodes
    * @author Thomas Brandstaetter <tb@essentialmind.com>
    * @version n/a
    * @since 11.05.2011
    * @copyright essentialmind.com 2011
    ***/
    class clientNodeEstateFolder extends clientNode {

        /**
         * @brief holds the type (! datatype) of an estate
         */
        private $estateType;

        /**
         * @brief will contain the federal states 
         */
        private $estateFederals = NULL;
        
        /*
         * @brief contain filters are set by the user
         */
        private $filter = array();
        
        /**
         * Process inputs
         * 
         * @return void 
         **/
        public function process(){           
            // first figure out the ID of the datatype responsible for gallery
            // images
            $this->setEstateType();
            $this->setFilters();
            
            //first I need to get the IDs of all child nodes of this folder

            /*
                Please note, that a whole array of all child nodes is fetched as well,
                as it will be passed to smarty in order to present on the interface
                that there exist subfolders in the selected folder
            */
            $myTree     = new tree($this->db,'structure LEFT JOIN objectmap ON structure.id = objectmap.nodeid',$this->log,'id, level, path_cache AS path, title, published_pages');
            $nodes      = $myTree->getChildren($this->node);            
            $children   = array();  // list of node IDs that lie below the current node
            $subcats    = array();  // list of direct subcategories i.e. no grandchildren
            
            //mark the level of the subcategories
            if(isset($nodes[0])){
                $curLevel   = $nodes[0]['level'];
            }
            
            $children[] = $this->node;  //add current node to the set limiter
            
            //loop through the node array and create associate markers to pass to smarty
            foreach($nodes as $node){
                $children[] = $node['id'];
                if($node['level'] == $curLevel){
                    $subcats[] = $node;   
                }
            }

            /*
                create the pager for this iFolder, in order to do this we need to
                first identify the total number of inserats there are in the
                currently selected folder
            */
            $total = $this->db->getOne("SELECT count(*)
                                                FROM pagemap AS pm 
                                                LEFT JOIN node_estate AS ne ON pm.pageid = ne.id
                                                WHERE pm.nodeid IN (".implode(',',$children).") 
                                                AND pm.wf_state = 1
                                                AND pm.pagetype = " . $this->estateType);
            
            $pager = new pager($total,$GLOBALS['_CONFIG']['perpage'],$_GET['pg']);
            
            /*
                the call to get the full path to the node may be
                a bit costly. This procedure may need refactoring
            */   
            $estates   = $this->db->getAll("SELECT 
                                                    pm.title AS title,
                                                    ne.*,
                                                    ew.name AS window,
                                                    ef.name AS floor,
                                                    ea.name AS accountrement,
                                                    eh.name AS heating,
                                                    et.name AS type,
                                                    ek.name AS kind,
                                                    (SELECT id FROM estate_pictures WHERE estate_id = ne.id ORDER BY order_pos LIMIT 1) AS main_image,
                                                    get_path(pm.nodeid)||pm.pageurl||'.html' AS url,
                                                    'files/pages/'||pm.pagetype||'__'||pm.pageid||'/image/' AS imagePath
                                                FROM pagemap AS pm 
                                                LEFT JOIN node_estate AS ne ON pm.pageid = ne.id
                                                LEFT JOIN estate_windows ew ON ew.id = ne.window_id
                                                LEFT JOIN estate_floors ef ON ef.id = ne.floor_id
                                                LEFT JOIN estate_accountrements ea ON ea.id = ne.accountrements_id
                                                LEFT JOIN estate_heatings eh ON eh.id = ne.heating_id
                                                LEFT JOIN estate_types et ON et.id = ne.type_id
                                                LEFT JOIN estate_kinds ek ON ek.id = ne.kind_id
                                                LEFT JOIN estate_federals efd ON efd.id = ne.federal_id
                                                WHERE pm.nodeid IN (".implode(',',$children).") 
                                                AND pm.pagetype = " . $this->estateType . "
                                                AND pm.wf_state = 1".
                                                (($this->filter['sm_up'] == NULL) ? " " : " AND ne.space >= ". $this->filter['sm_up'] . " ") .
                                                (($this->filter['sm_to'] == NULL) ? " " : " AND ne.space <= ". $this->filter['sm_to'] . " ") .
                                                (($this->filter['price_up'] == NULL) ? " " : " AND ne.price >= ". $this->filter['price_up'] . " ") .
                                                (($this->filter['price_to'] == NULL) ? " " : " AND ne.price <= ". $this->filter['price_to'] . " ") .
                                                (($this->filter['federal'] == NULL) ? " " : " AND ne.federal_id = ". $this->filter['federal'] . " ") .
                                                (($this->filter['room'] == NULL) ? " " : " AND ne.rooms >= ". $this->filter['room'] . " ") .
                                                (($this->filter['type'] == NULL) ? " " : " AND ne.type_id = ". $this->filter['type'] . " ") .
                                                (($this->filter['floor'] == NULL) ? " " : " AND ne.floor_id = ". $this->filter['floor'] . " ") .
                                                (($this->filter['kind'] == NULL) ? " " : " AND ne.kind_id = ". $this->filter['kind'] . " ") .
                                                "ORDER BY pm.published DESC
                                                LIMIT ".$GLOBALS['_CONFIG']['perpage']." OFFSET ".$_GET['offset']);  

            $children_ids = array();
            foreach ($estates as $e) {
                $children_ids []= $e['id'];
            }            
            
            //get folder properties if any
            $data = $this->db->getRow("SELECT * FROM node_estate_folder WHERE id = ".$this->object);
            $data['title'] = $this->db->getOne("SELECT title FROM objectmap WHERE nodeid = ".$this->node);

            //get actual folder data
            //assign all this stuff to smarty
            
            $children_ids = array_filter($children_ids, 'strlen');    // remove NULL
            $children_ids = array_filter($children_ids);              // remove false
            
            $this->smarty->assign(array(
                                        'estates'       => $estates,
                                        'filters'       => $this->filter,
                                        'childFolders'  => $subcats,
                                        'total'         => $total,
                                        'images'        => $images,
                                        'heatings'      => $this->distinctAssocProperties('estate_heatings', 'heating_id', $children_ids),
                                        'floors'        => $this->distinctAssocProperties('estate_floors', 'floor_id', $children_ids),
                                        'federals'      => $this->distinctAssocProperties('estate_federals', 'federal_id', $children_ids),
                                        'types'         => $this->distinctAssocProperties('estate_types', 'type_id', $children_ids),
                                        'rooms'         => ((empty($children_ids)) ? NULL : $this->db->getCol("SELECT distinct(rooms) FROM node_estate WHERE id IN (". implode(',', $children_ids) .")")),
                                        'pager'         => $pager->getPager()));
        }
        
        /**
         * distinct properties
         *
         * @brief This function returns all properties(properties are heating-, floor-, windowtype, ...) of an estate
         * in order to get all available ones in a set of estates (e.g. the current folder).
         * If ids param is empty null will be returnd
         *
         * @example distinctAssocProperties('estate_heatings', 'heating_id', array(1,2,3,4)) will fetch all heatings of the estates with the ids 1,2,3,4
         *
         * @param $table The name of the table where the 
         * @param $attrib The attribute in the estate node
         * @param $ids The node_estate ids to inspect 
         * @return null|array An array of distinct and available values in the given set
         */
        private function distinctAssocProperties($table, $attrib, $ids) {
            
            if (!implode(',',$ids)) 
                return NULL;
            
            $ids = array_filter($ids, 'strlen');
            $ids = array_filter($ids);
            
            return $this->db->getAll("SELECT t.*
                                FROM $table t
                                WHERE t.id IN (
                                                    SELECT distinct($attrib)
                                                    FROM node_estate ne
                                                    WHERE ne.id IN (".implode(',',$ids).") ) ");
        }
        
        /**
         * set the action template
         * 
         * @return void
         **/
        public function setTemplate(){ 
            $this->setActionTemplate('estatefolder.html');
        }
        
        /**
         * Sets the ID of an estatetype to this instance.
         * @detail Globals: this->estateType.
         *
         * @param void
         * @return void
         */
        private function setEstateType() {
            $this->estateType = (int)$this->db->getOne("SELECT id FROM datatype WHERE codeset = 'estate'");
            if($this->estateType == 0){
                throw new Exception("No estate datatype registered with the system!");   
            }
        }

        /**
         * @brief This function search for user defined filters in GET. All kinds of filters are stored to a corresponding hash key in
         * the $this->filters instance variable. hash keys are federal, price_up, price_to, sm_up (sm ... spare meter, area) sm_to, room
         * kind and type.
         * @details Globals $this->filters
         *
         * @param void
         * @return void
         */
        private function setFilters() {
                
                $this->filter['federal'] = (isset($_GET['bundesland'])) ? (int)$_GET['bundesland'] : NULL;
                $this->filter['price_up'] = (isset($_GET['preisvon'])) ?  (int)$_GET['preisvon'] :  NULL;
                $this->filter['price_to'] = (isset($_GET['preisbis'])) ?  (int)$_GET['preisbis'] : NULL;
                $this->filter['sm_up'] = (isset($_GET['qmvon']))    ? (int)$_GET['qmvon'] : NULL;
                $this->filter['sm_to'] = (isset($_GET['qmbis']))    ? (int)$_GET['qmbis'] : NULL;
                $this->filter['room'] = (isset($_GET['zimmer']))    ? (int)$_GET['zimmer'] : NULL;
                $this->filter['kind'] = (isset($_GET['kind']))      ? (int)$_GET['kind'] : NULL;
                $this->filter['type'] = (isset($_GET['type']))      ? (int)$_GET['type'] : NULL;
                $this->filter['floor'] = (isset($_GET['floor']))      ? (int)$_GET['floor'] : NULL;
        }
    }
?>
